import datetime
import json
import math
import os
import random
import string
import zipfile

from django.db.models import Q

import scanQrCode.models
from auther.functions.autherclass import get_trees
from auther.models import AdminUser
from employee.models import *
from scanQrCode.models import *
from functions.mysql_sql import mysql_function
from functions.mssql_sql import mssql_function
from utils.token import Token
from utils.ehr import EhrConnect


class EmpInfoFillIn:
    # def getDeptList(self, deptId):
    #     """
    #     获取人员部门列表
    #     :param deptId: 部门人员ID
    #     """
    #     dept_list = []
    #     dept_id = EmpDepartment.objects.filter(id=deptId).values('id', 'parent_id').first()
    #     while dept_id['parent_id'] != 0:
    #         # dept_list.append(dept_id['id'])
    #         dept_list.insert(0,dept_id['id'])
    #         dept_id = EmpDepartment.objects.filter(id=dept_id['parent_id']).values('id', 'parent_id').first()
    #     if len(dept_list) > 0:
    #         dept_list.insert(0,1)
    #     return dept_list

    def create_personal_files(self,id,now,idCard,idCardPicList,bankCardPicList,resumeFile,diplomaPicList,affixMaterialList,oneInchPic,dissmissPf):
        """
        创建人员文件
        :param id: 人员id
        :param now: 当前时间 为了修改文件修改时间
        :param idCard: 创建文件夹名称
        :param idCardPicList: 身份证件列表
        :param bankCardPicList: 银行卡证件列表
        :param resumeFile: 简历附件
        :param diplomaPicList: 学历证书列表
        :param affixMaterialList: 非用印文件列表
        :param oneInchPic: 一寸照片列表
        :param dissmissPf: 离职证明列表
        :return: 无
        """
        if not os.path.exists('static/empFiles/' + idCard):
            os.mkdir('static/empFiles/' + idCard)
        else:
            pass
        temp_id_card_list = []
        if len(idCardPicList) > 0:
            # 获取上一次的身份信息
            if not os.path.exists('static/empFiles/' + idCard + '/identityCard/'):
                os.mkdir('static/empFiles/' + idCard + '/identityCard/')
                for pics in idCardPicList:
                    temp_id_card_list.append('static/empFiles/' + idCard + '/identityCard/' + '身份证' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/identityCard/' + '身份证' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/identityCard',
                               outFullName='static/empFiles/' + idCard + '/身份证附件' + ".zip")
            else:
                for pics in idCardPicList:
                    temp_id_card_list.append('static/empFiles/' + idCard + '/identityCard/' + '身份证' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/identityCard/' + '身份证' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/identityCard',
                               outFullName='static/empFiles/' + idCard + '/身份证附件' + ".zip")

        '''银行卡照片（必要上传）'''
        temp_bank_card_list = []
        if len(bankCardPicList) > 0:
            # 获取上一次的身份信息
            if not os.path.exists('static/empFiles/' + idCard + '/bankCard/'):
                os.mkdir('static/empFiles/' + idCard + '/bankCard/')
                for pics in bankCardPicList:
                    temp_bank_card_list.append('static/empFiles/' + idCard + '/bankCard/' + '银行卡照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/bankCard/' + '银行卡照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/bankCard',
                               outFullName='static/empFiles/' + idCard + '/银行卡附件' + ".zip")

            else:
                for pics in bankCardPicList:
                    temp_bank_card_list.append('static/empFiles/' + idCard + '/bankCard/' + '银行卡照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/bankCard/' + '银行卡照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/bankCard',
                               outFullName='static/empFiles/' + idCard + '/银行卡附件' + ".zip")

        '''上传简历（非必要上传）'''
        temp_resume_list = []
        if len(resumeFile) > 0:
            # 获取上一次的身份信息
            if not os.path.exists('static/empFiles/' + idCard + '/resumeFiles/'):
                os.mkdir('static/empFiles/' + idCard + '/resumeFiles/')
                for resumes in resumeFile:
                    temp_resume_list.append('static/empFiles/' + idCard + '/resumeFiles/' + '简历' + '_' + str(resumes))
                    with open('static/empFiles/' + idCard + '/resumeFiles/' + '简历' + '_' + str(resumes), 'wb') as f:
                        for line in resumes.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/resumeFiles',
                               outFullName='static/empFiles/' + idCard + '/简历附件' + ".zip")

            else:
                for resumes in resumeFile:
                    temp_resume_list.append('static/empFiles/' + idCard + '/resumeFiles/' + '简历' + '_' + str(resumes))
                    with open('static/empFiles/' + idCard + '/resumeFiles/' + '简历' + '_' + str(resumes), 'wb') as f:
                        for line in resumes.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/resumeFiles',
                               outFullName='static/empFiles/' + idCard + '/简历附件' + ".zip")

        '''上传毕业证书照片(非必要上传)'''
        temp_diploma_list = []
        if len(diplomaPicList) > 0:
            if not os.path.exists('static/empFiles/' + idCard + '/diplomaFiles/'):
                os.mkdir('static/empFiles/' + idCard + '/diplomaFiles/')
                for pics in diplomaPicList:
                    temp_diploma_list.append('static/empFiles/' + idCard + '/diplomaFiles/' + '毕业证照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/diplomaFiles/' + '毕业证照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/diplomaFiles',
                               outFullName='static/empFiles/' + idCard + '/毕业证书附件' + ".zip")
            else:
                for pics in diplomaPicList:
                    temp_diploma_list.append('static/empFiles/' + idCard + '/diplomaFiles/' + '毕业证照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/diplomaFiles/' + '毕业证照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/diplomaFiles',
                               outFullName='static/empFiles/' + idCard + '/毕业证书附件' + ".zip")

        '''上传非用印材料（非必要上传）'''
        temp_affix_list = []
        if len(affixMaterialList) > 0:
            if not os.path.exists('static/empFiles/' + idCard + '/affixMaterialFiles/'):
                os.mkdir('static/empFiles/' + idCard + '/affixMaterialFiles/')
                for pics in affixMaterialList:
                    temp_affix_list.append(
                        'static/empFiles/' + idCard + '/affixMaterialFiles/' + '非用印材料' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/affixMaterialFiles/' + '非用印材料' + '_' + str(pics),
                              'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/affixMaterialFiles',
                               outFullName='static/empFiles/' + idCard + '/非用印材料附件' + ".zip")

            else:
                for pics in affixMaterialList:
                    temp_affix_list.append(
                        'static/empFiles/' + idCard + '/affixMaterialFiles/' + '非用印材料' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/affixMaterialFiles/' + '非用印材料' + '_' + str(pics),
                              'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/affixMaterialFiles',
                               outFullName='static/empFiles/' + idCard + '/非用印材料附件' + ".zip")

        '''上传一寸电子照片（必要上传）'''
        temp_oneInch_list = []
        if len(oneInchPic) > 0:
            if not os.path.exists('static/empFiles/' + idCard + '/oneInchFiles/'):
                os.mkdir('static/empFiles/' + idCard + '/oneInchFiles/')
                for pics in oneInchPic:
                    temp_oneInch_list.append(
                        'static/empFiles/' + idCard + '/oneInchFiles/' + '一寸电子照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/oneInchFiles/' + '一寸电子照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/oneInchFiles',
                               outFullName='static/empFiles/' + idCard + '/一寸照片附件' + ".zip")

            else:
                for pics in oneInchPic:
                    temp_oneInch_list.append(
                        'static/empFiles/' + idCard + '/oneInchFiles/' + '一寸电子照片' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/oneInchFiles/' + '一寸电子照片' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/oneInchFiles',
                               outFullName='static/empFiles/' + idCard + '/一寸照片附件' + ".zip")

        '''上传离职证明（非必要上传）'''
        temp_dissmissPf_list = []
        if len(dissmissPf)>0:
            if not os.path.exists('static/empFiles/' + idCard + '/dissmissPfFiles/'):
                os.mkdir('static/empFiles/' + idCard + '/dissmissPfFiles/')
                for pics in dissmissPf:
                    temp_dissmissPf_list.append(
                        'static/empFiles/' + idCard + '/dissmissPfFiles/' + '离职证明' + '_' + str(pics))
                    print(temp_dissmissPf_list)
                    with open('static/empFiles/' + idCard + '/dissmissPfFiles/' + '离职证明' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/dissmissPfFiles',
                               outFullName='static/empFiles/' + idCard + '/离职证明附件' + ".zip")
            else:
                for pics in dissmissPf:
                    temp_dissmissPf_list.append(
                        'static/empFiles/' + idCard + '/dissmissPfFiles/' + '离职证明' + '_' + str(pics))
                    with open('static/empFiles/' + idCard + '/dissmissPfFiles/' + '离职证明' + '_' + str(pics), 'wb') as f:
                        for line in pics.chunks():
                            f.write(line)
                    f.close()
                self.getZipDir(dirpath='static/empFiles/' + idCard + '/dissmissPfFiles',
                               outFullName='static/empFiles/' + idCard + '/离职证明附件' + ".zip")

        '''身份证照片写入'''
        if len(temp_id_card_list) > 0:
            for idCardPic in temp_id_card_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=idCardPic,
                                                files_type_id=1, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=idCardPic,
                                             files_type_id=1)
        '''银行卡照片写入'''
        if len(temp_bank_card_list) > 0:
            for bankCardPic in temp_bank_card_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=bankCardPic,
                                                files_type_id=2, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=bankCardPic,
                                             files_type_id=2)
        '''简历文件写入'''
        if len(temp_resume_list) > 0:
            for resume in temp_resume_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=resume,
                                                files_type_id=3, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=resume, files_type_id=3)
        '''毕业证书写入'''
        if len(temp_diploma_list) > 0:
            for diploma in temp_diploma_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=diploma,
                                                files_type_id=4, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=diploma, files_type_id=4)
        '''非用印材料写入'''
        if len(temp_affix_list) > 0:
            for affix in temp_affix_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=affix,
                                                files_type_id=5, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=affix, files_type_id=5)
        '''一寸电子照片写入'''
        if len(temp_oneInch_list) > 0:
            for oneInch in temp_oneInch_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=oneInch,
                                                files_type_id=6, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=oneInch, files_type_id=6)
        '''离职证明写入'''
        if len(temp_dissmissPf_list) > 0:
            for dismiss in temp_dissmissPf_list:
                try:
                    obj = ScanFiles.objects.get(files_person_id=id, files_url=dismiss,files_type_id=7, files_status=True)
                    obj.files_modifiy_time = now
                    obj.save()
                except ScanFiles.DoesNotExist:
                    ScanFiles.objects.create(files_person_id=id, files_url=dismiss, files_type_id=7)


    def getZipDir(self, dirpath, outFullName):
        """
        压缩指定文件夹
        :param dirpath: 目标文件夹路径
        :param outFullName: 压缩文件保存路径+xxxx.zip
        :return: 无
        """
        zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dirpath):
            # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
            fpath = path.replace(dirpath, '')

            for filename in filenames:
                zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
        zip.close()

    def get_urgent_relation(self, num):
        """
        获取与紧急联系人关系
        :param num: 表示发送的人员关系
        :return: 1：父母 2：配偶 3：兄弟姐妹 4：其他
        """
        numbers = {
            '1': "父母",
            '2': "配偶",
            '3': "兄弟姐妹",
            '4': "其他",
        }
        return numbers.get(num, None)

    def show_urgent_relation(self, num):
        """
        展示与紧急联系人关系
        :param num: 表示发送的人员关系
        :return: 1：父母 2：配偶 3：兄弟姐妹 4：其他
        """
        numbers = {
            '父母': "1",
            '配偶': "2",
            '兄弟姐妹': "3",
            '其他': "4",
        }
        return numbers.get(num, None)

    def create_string_number(self, n):
        m = random.randint(1, n)
        a = "".join([str(random.randint(0, 9)) for _ in range(m)])
        b = "".join([random.choice(string.ascii_letters) for _ in range(n - m)])
        return ''.join(random.sample(list(a + b), n))

    def empInfoFillIn(self, idCard, name, code, politicsStatus, nationality, nationId, domicileAddress, nativePlaceId,
                      latestAddress, marriage, urgentPerson, urgentPersonPhone, urgentRelation,
                      firstDegreeId, graduateTime, graduateInsituation, major, educateMethod, bankIdCard, openBank,
                      idCardPicList, bankCardPicList, resumeFile, phone, diplomaPicList, dissmissPf,
                      oneInchPic, affixMaterialList):
        # 人员信息填写
        err_msg = ''
        nowTime = datetime.datetime.now().strptime(str(datetime.datetime.now())[:10], '%Y-%m-%d')
        return_data = {'code': "", "message": ""}
        if idCard is None or idCard is "":
            err_msg = err_msg + '请输入身份证'
        elif len(idCard) != 18:
            err_msg = err_msg + '请输入18位数身份证,现在仅有' + ' ' + str(len(idCard)) + ' ' + '位'
        else:
            last_second_num = idCard[-2:-1]
            if int(last_second_num) % 2 == 0:
                gender = 2  # 0 偶数 表示女
            else:
                gender = 1  # 1 奇数 表示男
            birth_year = idCard[6:10]
            birth_month = idCard[10:12]
            birth_day = idCard[12:14]
            birth_time = datetime.datetime.strptime(birth_year + '-' + birth_month + '-' + birth_day, '%Y-%m-%d')
        # 身份证位数是否是18位
        if name is None or name is "" or name is 'undefined':
            err_msg = err_msg + '请输入您的姓名,'
        if code is None or code is "" or code is 'undefined':
            err_msg = err_msg + '请输入您的工号,'
        if len(code) != 10:
            err_msg = err_msg + '请输入10位数的工号,'
        if len(phone) != 11:
            err_msg = err_msg + '请输入11位数的电话号码,'
        if len(urgentPersonPhone) != 11:
            err_msg = err_msg + '请输入11位数的紧急联系人电话号码,'
        if err_msg != '':
            return_data['code'] = 400
            return_data['message'] = err_msg[:-1]
            return return_data
        now = datetime.datetime.now()
        # 根据身份证号获取该人的最新一条记录
        emp_latest_info = ScanEmployee.objects.filter(emp_id_card=idCard).values('id','emp_id_card','emp_name','emp_predict_entry_date','emp_approve_status').order_by('-id')[0]
        # 如果这一个最近的记录不是未审批或者已驳回就不允许该人员进行填写
        if emp_latest_info['emp_approve_status'] != 1 and emp_latest_info['emp_approve_status'] != 3:
            return_data['code'] = 400
            return_data['message'] = '您最近投递的简历已审核通过无需填写'
            return return_data
        if len(emp_latest_info) > 0:
            try:
                # 获取最新的一条记录对象 (身份证输入正确)
                emp_obj = ScanEmployee.objects.get(id=emp_latest_info['id'])
                # 根据获取最新的数据对象来比较时间：今天的年月日和当前对象创建时间的年月日进行比较
                obj_emp_predict_entry_date = emp_obj.emp_predict_entry_date.strptime(str(emp_obj.emp_predict_entry_date)[:10], '%Y-%m-%d')
                if str(nowTime)[:10] == str(obj_emp_predict_entry_date)[:10]:  # 如果今天和该对象创建的时间是同一天 表示记录就是今天导入的
                    emp_obj.emp_gender = gender
                    emp_obj.emp_code = code  # 人员工号
                    emp_obj.emp_political_affiliation = politicsStatus  # 政治面貌
                    emp_obj.emp_nationality = nationality  # 国籍
                    emp_obj.emp_native_place_id = nativePlaceId  # 籍贯
                    emp_obj.emp_ethnic_id = nationId  # 民族id
                    emp_obj.emp_educate_method = educateMethod  # 全日制非全日制
                    emp_obj.emp_domicile_address = domicileAddress  # 户籍地址
                    emp_obj.emp_latest_address = latestAddress  # 现住址
                    emp_obj.emp_marriage = marriage  # 婚姻状况
                    emp_obj.emp_urgent_person = urgentPerson  # 紧急联系人
                    emp_obj.emp_urgent_phone = urgentPersonPhone  # 紧急联系人电话
                    emp_obj.emp_urgent_relation = self.get_urgent_relation(urgentRelation)  # 紧急联系人关系
                    emp_obj.emp_first_degree_id = firstDegreeId  # 第一学历
                    emp_obj.emp_gradute_time = graduateTime  # 毕业时间
                    emp_obj.emp_gradute_insituation = graduateInsituation  # 毕业院校
                    emp_obj.emp_major = major  # 专业
                    emp_obj.emp_bank_card_num = bankIdCard  # 银行卡号
                    emp_obj.emp_bank = openBank  # 开户行
                    emp_obj.emp_name = name
                    emp_obj.emp_birthday = birth_time
                    emp_obj.emp_phone = phone
                    emp_obj.emp_if_fill_in = True
                    # 调用创建文件的接口
                    self.create_personal_files(emp_obj.id,now,idCard,idCardPicList,bankCardPicList,resumeFile,diplomaPicList,affixMaterialList,oneInchPic,dissmissPf)
                    emp_obj.save()
                else:
                    # 表示不是几天入职的白名单人员 需要到大名单中找到是否有这个人
                    # 在大名单中找到了白名单人员 更新预计入职时间
                    emp_obj.emp_gender = gender
                    emp_obj.emp_predict_entry_date = nowTime
                    emp_obj.emp_code = code  # 人员工号
                    emp_obj.emp_political_affiliation = politicsStatus  # 政治面貌
                    emp_obj.emp_nationality = nationality  # 国籍
                    emp_obj.emp_native_place_id = nativePlaceId  # 籍贯
                    emp_obj.emp_ethnic_id = nationId  # 民族id
                    emp_obj.emp_educate_method = educateMethod  # 全日制非全日制
                    emp_obj.emp_domicile_address = domicileAddress  # 户籍地址
                    emp_obj.emp_latest_address = latestAddress  # 现住址
                    emp_obj.emp_marriage = marriage  # 婚姻状况
                    emp_obj.emp_urgent_person = urgentPerson  # 紧急联系人
                    emp_obj.emp_urgent_phone = urgentPersonPhone  # 紧急联系人电话
                    emp_obj.emp_urgent_relation = self.get_urgent_relation(urgentRelation)  # 紧急联系人关系
                    emp_obj.emp_first_degree_id = firstDegreeId  # 第一学历
                    emp_obj.emp_gradute_time = graduateTime  # 毕业时间
                    emp_obj.emp_gradute_insituation = graduateInsituation  # 毕业院校
                    emp_obj.emp_major = major  # 专业
                    emp_obj.emp_bank_card_num = bankIdCard  # 银行卡号
                    emp_obj.emp_bank = openBank  # 开户行
                    emp_obj.emp_name = name
                    emp_obj.emp_birthday = birth_time
                    emp_obj.emp_phone = phone
                    emp_obj.emp_if_fill_in = True
                    self.create_personal_files(emp_obj.id,now,idCard,idCardPicList,bankCardPicList,resumeFile,diplomaPicList,affixMaterialList,oneInchPic,dissmissPf)
                    emp_obj.save()
            except ScanEmployee.DoesNotExist:  # 不存在最新的一条记录,直接创建
                return_data['code'] = 400
                return_data['message'] = '请先投递简历，再进行入职'
                return return_data
        else:
            # 如果没有找到最近面试记录不允许入职
            return_data['code'] = 400
            return_data['message'] = '请先投递简历，再进行入职'
            return return_data
        # 判断是暂存还是提交 获取当天的时间点八点和下午两点
        zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,microseconds=now.microsecond)
        today_eight = zero_today + datetime.timedelta(hours=8, minutes=00, seconds=00)
        today_two = zero_today + datetime.timedelta(hours=14, minutes=00, seconds=00)
        if now >= today_eight and now <= today_two:
            return_data['code'] = 200
            return_data['message'] = '提交成功'
            return return_data
        else:
            return_data['code'] = 200
            return_data['message'] = '已暂存'
            return return_data

    '''根据身份证信息返回人员填写的信息'''

    def empFillInQuery(self, idCard):
        # 根据身份证号码找到这个人最近的填写记录
        return_data = {'code': "", "message": ""}
        emp_latest_info = ScanEmployee.objects.filter(emp_id_card=idCard, emp_approve_status__in=[1, 3]).values('id', 'emp_id_card', 'emp_name', 'emp_create_time', 'emp_if_fill_in').order_by('-id')
        if emp_latest_info:
            '''直接返回个人信息'''
            # 身份证照片
            id_card_list = []
            id_card_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],files_type_id=1).values('files_url')
            if id_card_obj.exists():
                for id_card_img in id_card_obj:
                    temp_dic = {
                        "name": id_card_img['files_url'].split("/")[len(id_card_img["files_url"].split("/")) - 1],
                        "extname": id_card_img["files_url"].split(".")[
                            len(id_card_img["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + id_card_img["files_url"],
                    }
                    id_card_list.append(temp_dic)
            # 银行卡复印件
            bank_card_list = []
            bank_card_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                     files_type_id=2).values('files_url')
            if bank_card_obj.exists():
                for bank_card_img in bank_card_obj:
                    temp_dic = {
                        "name": bank_card_img['files_url'].split("/")[
                            len(bank_card_img["files_url"].split("/")) - 1],
                        "extname": bank_card_img["files_url"].split(".")[
                            len(bank_card_img["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + bank_card_img["files_url"],
                    }
                    bank_card_list.append(temp_dic)
            # 简历文件
            resume_list = []
            resume_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                  files_type_id=3).values('files_url')
            if resume_obj.exists():
                for resume in resume_obj:
                    temp_dic = {
                        "name": resume['files_url'].split("/")[len(resume["files_url"].split("/")) - 1],
                        "extname": resume["files_url"].split(".")[len(resume["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + resume["files_url"],
                    }
                    resume_list.append(temp_dic)
            # 学历证书
            diploma_list = []
            diploma_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                   files_type_id=4).values('files_url')
            if diploma_obj.exists():
                for diploma in diploma_obj:
                    temp_dic = {
                        "name": diploma['files_url'].split("/")[len(diploma["files_url"].split("/")) - 1],
                        "extname": diploma["files_url"].split(".")[len(diploma["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + diploma["files_url"],
                    }
                    diploma_list.append(temp_dic)
            # 离职证明
            dissmiss_list = []
            dissmiss_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                    files_type_id=7).values('files_url')
            if dissmiss_obj.exists():
                for dissmiss in dissmiss_obj:
                    temp_dic = {
                        "name": dissmiss['files_url'].split("/")[len(dissmiss["files_url"].split("/")) - 1],
                        "extname": dissmiss["files_url"].split(".")[len(dissmiss["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + dissmiss["files_url"],
                    }
                    dissmiss_list.append(temp_dic)
            # 一寸照片
            oneInch_list = []
            oneInch_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                   files_type_id=6).values('files_url')
            if oneInch_obj.exists():
                for oneInch in oneInch_obj:
                    temp_dic = {
                        "name": oneInch['files_url'].split("/")[len(oneInch["files_url"].split("/")) - 1],
                        "extname": oneInch["files_url"].split(".")[len(oneInch["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + oneInch["files_url"],
                    }
                    oneInch_list.append(temp_dic)
            # 非用印材料
            affix_list = []
            affix_obj = ScanFiles.objects.filter(files_status=True, files_person_id=emp_latest_info[0]['id'],
                                                 files_type_id=5).values('files_url')
            if affix_obj.exists():
                for affix in affix_obj:
                    temp_dic = {
                        "name": affix['files_url'].split("/")[len(affix["files_url"].split("/")) - 1],
                        "extname": affix["files_url"].split(".")[len(affix["files_url"].split(".")) - 1],
                        "url": "http://172.16.12.204:8011/" + affix["files_url"],
                    }
                    affix_list.append(temp_dic)

            emp_info = ScanEmployee.objects.get(id=emp_latest_info[0]['id'])
            temp_dic = {
                'idCard': emp_info.emp_id_card,
                'phone': emp_info.emp_phone if emp_info.emp_phone is not None else '',
                'name': emp_info.emp_name if emp_info.emp_name is not None else '',
                'code': emp_info.emp_code if emp_info.emp_code is not None else '',
                'politicsStatus': emp_info.emp_political_affiliation if emp_info.emp_political_affiliation is not None else '',
                'nationality': emp_info.emp_nationality if emp_info.emp_nationality is not None else '',
                'nationId': emp_info.emp_ethnic_id if emp_info.emp_ethnic_id is not None else '',
                'domicileAddress': emp_info.emp_domicile_address if emp_info.emp_domicile_address is not None else '',
                'nativePlaceId': emp_info.emp_native_place_id if emp_info.emp_native_place_id is not None else '',
                'latestAddress': emp_info.emp_latest_address if emp_info.emp_latest_address is not None else '',
                'marriage': emp_info.emp_marriage if emp_info.emp_marriage is not None else '',
                'urgentPerson': emp_info.emp_urgent_person if emp_info.emp_urgent_person is not None else '',
                'urgentPersonPhone': emp_info.emp_urgent_phone if emp_info.emp_urgent_phone is not None else '',
                'urgentRelation': self.show_urgent_relation(emp_info.emp_urgent_relation) if emp_info.emp_urgent_relation is not None else '',
                'firstDegreeId': emp_info.emp_first_degree_id if emp_info.emp_first_degree_id is not None else '',
                'graduateTime': str(emp_info.emp_gradute_time)[:10] if emp_info.emp_gradute_time is not None else '',
                'graduateInsituation': emp_info.emp_gradute_insituation if emp_info.emp_gradute_insituation is not None else '',
                'major': emp_info.emp_major if emp_info.emp_major is not None else '',
                'educateMethod': emp_info.emp_educate_method if emp_info.emp_educate_method is not None else '',
                'bankIdCard': emp_info.emp_bank_card_num if emp_info.emp_bank_card_num is not None else '',
                'openBank': emp_info.emp_bank if emp_info.emp_bank is not None else '',
                'predictEntryTime': str(emp_info.emp_predict_entry_date)[:10] if emp_info.emp_predict_entry_date is not None else '',
                'idCardPicList': id_card_list,
                'bankCardPicList': bank_card_list,
                'resumeFile': resume_list,
                'diplomaPicList': diploma_list,
                'dissmissPf': dissmiss_list,
                'oneInchPic': oneInch_list,
                'affixMaterialList': affix_list,
            }
            return_data['data'] = temp_dic
            return_data['code'] = 200
            return_data['message'] = '信息返回成功'
            return return_data
        else:
            return_data['code'] = 400
            return_data['message'] = '请先投递简历，再进行入职'
            return return_data

    '''扫码入职当天人员勾选批量导入EHR'''

    def empInfoImport(self, idList):
        now = datetime.datetime.now()
        zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,microseconds=now.microsecond)
        # last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
        # 获取传过来人员的id
        obj_list = ScanEmployee.objects.filter(id__in=idList).values('emp_name', 'emp_code', 'emp_entry_date',
                                                                     'emp_dept', 'emp_post', 'emp_job_duty',
                                                                     'emp_job_class', 'emp_job_grade', 'emp_job_rank',
                                                                     'emp_ethnic', 'emp_native_place', 'emp_pay_type',
                                                                     'emp_first_degree', 'emp_id_card', 'emp_gender',
                                                                     'emp_marriage', 'emp_birthday',
                                                                     'emp_phone', 'emp_grade', 'emp_dl_idl',
                                                                     'emp_labour_source', 'emp_political_affiliation',
                                                                     'emp_nationality',
                                                                     'emp_domicile_address', 'emp_latest_address',
                                                                     'emp_urgent_person', 'emp_urgent_phone',
                                                                     'emp_urgent_relation', 'emp_gradute_time',
                                                                     'emp_gradute_insituation', 'emp_major',
                                                                     'emp_educate_method', 'emp_bank_card_num',
                                                                     'emp_bank')
        if obj_list.exists():
            for empInfo in obj_list:
                # 寻找到最新的一条属于该人员的记录：如果有这一条记录就更新记录如果没有就插入一条记录
                latest_record = mssql_function(
                    "select * from T_HR_Employee where _jtrzrq='%s' and identityNumber='%s'" % (
                        str(zero_today), empInfo['emp_id_card']), 'select')
                if len(latest_record) == 0:
                    get_max_id = mssql_function("select max(ID) from T_HR_Employee where 1=1", 'select')
                    maxID = get_max_id[0][0] + 1
                    mssql_function(
                        "insert into T_HR_Employee(ID,Name,_jtrzrq,DeptID,PostID,JobID,JobClassID,JobGradeID,JobRankID,identityNumber,Sex,Birthday,phone,_gsgs,PayTypeID,_dlidl,qq,Code,_zzmm,_gj,NationID,HomeAddress,_xzz,HomeID,marriage,_jjlxr,_lxrdh,_guanxi,DegreeID,_bysj,_yuanxiao,_zhuanye,_jyfs,_kahao,_khh) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
                            maxID, empInfo['emp_name'], str(empInfo['emp_entry_date']) + '.000', empInfo['emp_dept'],
                            empInfo['emp_post'],
                            empInfo['emp_job_duty'],
                            empInfo['emp_job_class'], empInfo['emp_job_grade'], empInfo['emp_job_rank'],
                            empInfo['emp_id_card'],
                            empInfo['emp_gender'], str(empInfo['emp_birthday']) + '.000', empInfo['emp_phone'],
                            empInfo['emp_grade'],
                            empInfo['emp_pay_type'], empInfo['emp_dl_idl'], empInfo['emp_labour_source'],
                            empInfo['emp_code'],
                            empInfo['emp_political_affiliation'], empInfo['emp_nationality'], empInfo['emp_ethnic'],
                            empInfo['emp_domicile_address'],
                            empInfo['emp_latest_address'], empInfo['emp_native_place'], empInfo['emp_marriage'],
                            empInfo['emp_urgent_person'], empInfo['emp_urgent_phone'], empInfo['emp_urgent_relation'],
                            empInfo['emp_first_degree'], str(empInfo['emp_gradute_time']) + '.000',
                            empInfo['emp_gradute_insituation'],
                            empInfo['emp_major'], empInfo['emp_educate_method'], empInfo['emp_bank_card_num'],
                            empInfo['emp_bank']), 'insert')
                else:
                    mssql_function(
                        "Update T_HR_Employee set Name='%s',_jtrzrq='%s',DeptID='%s',PostID='%s',JobID='%s',JobClassID='%s',JobGradeID='%s',JobRankID='%s',identityNumber='%s',Sex='%s',Birthday='%s',phone='%s',_gsgs='%s',PayTypeID='%s',_dlidl='%s',qq='%s',Code='%s',_zzmm='%s',_gj='%s',NationID='%s',HomeAddress='%s',_xzz='%s',HomeID='%s',marriage='%s',_jjlxr='%s',_lxrdh='%s',_guanxi='%s',DegreeID='%s',_bysj='%s',_yuanxiao='%s',_zhuanye='%s',_jyfs='%s',_kahao='%s',_khh='%s' where _jtrzrq='%s'" % (
                            empInfo['emp_name'], str(empInfo['emp_entry_date']) + '.000', empInfo['emp_dept'],
                            empInfo['emp_post'],
                            empInfo['emp_job_duty'],
                            empInfo['emp_job_class'], empInfo['emp_job_grade'], empInfo['emp_job_rank'],
                            empInfo['emp_id_card'],
                            empInfo['emp_gender'], str(empInfo['emp_birthday']) + '.000', empInfo['emp_phone'],
                            empInfo['emp_grade'],
                            empInfo['emp_pay_type'], empInfo['emp_dl_idl'], empInfo['emp_labour_source'],
                            empInfo['emp_code'],
                            empInfo['emp_political_affiliation'], empInfo['emp_nationality'], empInfo['emp_ethnic'],
                            empInfo['emp_domicile_address'],
                            empInfo['emp_latest_address'], empInfo['emp_native_place'], empInfo['emp_marriage'],
                            empInfo['emp_urgent_person'], empInfo['emp_urgent_phone'], empInfo['emp_urgent_relation'],
                            empInfo['emp_first_degree'], str(empInfo['emp_gradute_time']) + '.000',
                            empInfo['emp_gradute_insituation'],
                            empInfo['emp_major'], empInfo['emp_educate_method'], empInfo['emp_bank_card_num'],
                            empInfo['emp_bank'], str(zero_today)), 'insert')

    '''白名单人员修改'''

    def whiteListPersonModify(self, id,empName,empCode,empEntryDate,deptId,postId,jobDutyId,jobClassId,jobGradeId,jobRankId,empGrade,empPredictEntryDate,ethnicId,nativePlaceId,payTypeId,firstDegreeId,empIdCard,empGender,empMarriage,empBirthDay,empPhone,empDlIDL,empLaborSource,empPoliticalAffiliation,empNationality,empDomicileAddress,empLatestAddress,empUrgentPerson,empUrgentPhone,empUrgentRelation,empGraduateTime,empGraduateInsituation,empMajor,empEducateMethod,empBankCardNum,empBank):
        return_data = {'code': "", "msg": ""}
        # 根据ID获取白名单人员的信息
        try:
            emp_obj = ScanEmployee.objects.get(id=id)
            emp_obj.emp_name = empName
            emp_obj.emp_code = empCode
            if empEntryDate != '':  # 如果公司入职日期不为空
                emp_obj.emp_entry_date = empEntryDate
            emp_obj.emp_dept_id = deptId
            emp_obj.emp_post_id = postId
            if jobDutyId != '':  # 根据职务将职等 职级 变为空值
                emp_obj.emp_job_duty_id = jobDutyId
                emp_obj.emp_job_class_id = emp_obj.emp_job_duty.job_duty_class_id
                emp_obj.emp_job_grade_id = emp_obj.emp_job_duty.job_duty_grade_id
            else:
                emp_obj.emp_job_duty_id = None
                emp_obj.emp_job_class_id = None
                emp_obj.emp_job_grade_id = None
            emp_obj.emp_job_rank_id = jobRankId
            emp_obj.emp_grade = empGrade
            if empPredictEntryDate != 0:
                emp_obj.emp_predict_entry_date = empPredictEntryDate
            emp_obj.emp_ethnic_id = ethnicId
            emp_obj.emp_native_place_id = nativePlaceId
            emp_obj.emp_pay_type_id = payTypeId
            emp_obj.emp_first_degree_id = firstDegreeId
            emp_obj.emp_id_card = empIdCard
            if empGender!='':
                emp_obj.emp_gender = empGender
            else:
                emp_obj.emp_gender = None
            emp_obj.emp_marriage = empMarriage
            if empBirthDay != '':
                emp_obj.emp_birthday = empBirthDay
            else:
                emp_obj.emp_birthday = None
            emp_obj.emp_phone = empPhone
            emp_obj.emp_dl_idl = empDlIDL
            emp_obj.emp_labour_source = empLaborSource
            emp_obj.emp_political_affiliation = empPoliticalAffiliation
            emp_obj.emp_nationality = empNationality
            emp_obj.emp_domicile_address = empDomicileAddress
            emp_obj.emp_latest_address = empLatestAddress
            emp_obj.emp_urgent_person = empUrgentPerson
            emp_obj.emp_urgent_phone = empUrgentPhone
            emp_obj.emp_urgent_relation = empUrgentRelation
            if empGraduateTime != '':
                emp_obj.emp_gradute_time = empGraduateTime
            else:
                emp_obj.emp_gradute_time = None
            emp_obj.emp_gradute_insituation = empGraduateInsituation
            emp_obj.emp_major = empMajor
            emp_obj.emp_educate_method = empEducateMethod
            emp_obj.emp_bank_card_num = empBankCardNum
            emp_obj.emp_bank = empBank
            emp_obj.save()
            return_data['code'] = 200
            return_data['msg'] = '修改成功'
        except ScanEmployee.DoesNotExist:
            return_data['code'] = 400
            return_data['msg'] = '人员不存在'
        return return_data

    '''人员查询'''

    def whiteListPerson(self, token, emp_info, search_date, limit, page):
        approve_status_choices = {1: '未审批', 2: '已完成', 3: '已驳回', }
        return_data = {'code': 200, 'msg': '', 'data': [], 'pageCount': ''}
        token_class = Token()
        token_class.token = token
        user_id = token_class.check_token()
        if user_id:
            kwargs = {}
            args = ()
            if emp_info != '':
                args = args + (Q(emp_code__contains=emp_info) | Q(emp_name__contains=emp_info),)
            if search_date:
                kwargs['emp_predict_entry_date__range'] = search_date
            white_person_list = ScanEmployee.objects.filter(*args, **kwargs).values('id',
                                                                                    'emp_name',
                                                                                    'emp_code',
                                                                                    'emp_entry_date',
                                                                                    'emp_dept__department_name',
                                                                                    'emp_post__post_name',
                                                                                    'emp_job_duty__job_duty_name',
                                                                                    'emp_job_duty__job_duty_class__job_class_name',
                                                                                    'emp_job_duty__job_duty_grade__job_grade_name',
                                                                                    'emp_job_rank__job_rank_name',
                                                                                    'emp_ethnic__enthic_name',
                                                                                    'emp_native_place__native_name',
                                                                                    'emp_pay_type__pay_type_name',
                                                                                    'emp_first_degree__first_degree_name',
                                                                                    'emp_id_card',
                                                                                    'emp_gender',
                                                                                    'emp_marriage',
                                                                                    'emp_birthday',
                                                                                    'emp_phone',
                                                                                    'emp_grade',
                                                                                    'emp_dl_idl',
                                                                                    'emp_labour_source',
                                                                                    'emp_political_affiliation',
                                                                                    'emp_nationality',
                                                                                    'emp_domicile_address',
                                                                                    'emp_latest_address',
                                                                                    'emp_urgent_person',
                                                                                    'emp_urgent_phone',
                                                                                    'emp_urgent_relation',
                                                                                    'emp_gradute_time',
                                                                                    'emp_gradute_insituation',
                                                                                    'emp_major',
                                                                                    'emp_educate_method',
                                                                                    'emp_bank_card_num',
                                                                                    'emp_bank',
                                                                                    'emp_predict_entry_date',
                                                                                    'emp_approve_status', 'emp_dept_id',
                                                                                    'emp_post_id', 'emp_job_duty_id',
                                                                                    'emp_job_duty__job_duty_class_id',
                                                                                    'emp_job_duty__job_duty_grade_id',
                                                                                    'emp_job_rank_id',
                                                                                    'emp_pay_type_id','emp_ethnic_id','emp_first_degree_id','emp_native_place_id').order_by('-id')[(page - 1) * limit:limit * page]
            if white_person_list.exists():
                return_data['code'] = 200
                return_data['msg'] = '获取人员信息成功'
                return_data['pageCount'] = ScanEmployee.objects.filter(*args, **kwargs).count()
                for index, emp in enumerate(white_person_list):
                    # 根据人员的身份证去获取文件
                    identityCardNum = 0  # 身份证附件数量
                    bankCardNum = 0  # 银行卡附件数量
                    resumeFilesNum = 0  # 简历附件数量
                    diplomaFilesNum = 0  # 学历证书数量
                    affixMaterialNum = 0  # 非用印材料数量
                    oneInchFilesNum = 0  # 一寸照片材料数量
                    dissmissPfNum = 0  # 离职证明材料数量
                    try:
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/identityCard'):
                            identityCardNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/identityCard'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/bankCard'):
                            bankCardNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/bankCard'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/resumeFiles'):
                            resumeFilesNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/resumeFiles'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/diplomaFiles'):
                            diplomaFilesNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/diplomaFiles'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/affixMaterialFiles'):
                            affixMaterialNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/affixMaterialFiles'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/oneInchFiles'):
                            oneInchFilesNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/oneInchFiles'))
                        if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/dissmissPfFiles'):
                            dissmissPfNum = len(os.listdir('static/empFiles/' + emp['emp_id_card'] + '/dissmissPfFiles'))
                    except KeyError:
                        pass
                    temp_dic = {
                        'index': (page - 1) * limit + index + 1,
                        'id': emp['id'],
                        'empName': emp['emp_name'] if emp['emp_name'] is not None else '',
                        'empCode': emp['emp_code'] if emp['emp_code'] is not None else '',
                        'empEntryDate': str(emp['emp_entry_date'])[:10] if emp['emp_entry_date'] is not None else '',
                        'deptId': emp['emp_dept_id'] if emp['emp_dept_id'] is not None else '',
                        'empDeptName': emp['emp_dept__department_name'] if emp['emp_dept__department_name'] is not None else '',
                        'postId': emp['emp_post_id'] if emp['emp_post_id'] is not None else '',
                        'empPostName': emp['emp_post__post_name'] if emp['emp_post__post_name'] is not None else '',
                        'jobRankId': emp['emp_job_rank_id'] if emp['emp_job_rank_id'] is not None else '',
                        'empJobRank': emp['emp_job_rank__job_rank_name'] if emp['emp_job_rank__job_rank_name'] is not None else '',
                        'jobDutyId': emp['emp_job_duty_id'] if emp['emp_job_duty_id'] is not None else '',
                        'empJobDutyName': emp['emp_job_duty__job_duty_name'] if emp['emp_job_duty__job_duty_name'] is not None else '',
                        'jobClassId': emp['emp_job_duty__job_duty_class_id'] if emp['emp_job_duty__job_duty_class_id'] is not None else '',
                        'empJobClassName': emp['emp_job_duty__job_duty_class__job_class_name'] if emp['emp_job_duty__job_duty_class__job_class_name'] is not None else '',
                        'jobGradeId': emp['emp_job_duty__job_duty_grade_id'] if emp['emp_job_duty__job_duty_grade_id'] is not None else '',
                        'empJobGradeName': emp['emp_job_duty__job_duty_grade__job_grade_name'] if emp['emp_job_duty__job_duty_grade__job_grade_name'] is not None else '',
                        'empEthnicName': emp['emp_ethnic__enthic_name'] if emp['emp_ethnic__enthic_name'] is not None else '',
                        'nativePlaceId':emp['emp_native_place_id'] if emp['emp_native_place_id'] is not None else '',
                        'empNativePlace': emp['emp_native_place__native_name'] if emp['emp_native_place__native_name'] is not None else '',
                        'payTypeId': emp['emp_pay_type_id'] if emp['emp_pay_type_id'] is not None else '',
                        'empPayTypeName': emp['emp_pay_type__pay_type_name'] if emp['emp_pay_type__pay_type_name'] is not None else '',
                        'firstDegreeId': emp['emp_first_degree_id'] if emp['emp_first_degree_id'] is not None else '',
                        'empFirstDegreeName': emp['emp_first_degree__first_degree_name'] if emp['emp_first_degree__first_degree_name'] is not None else '',
                        'empIdCard': emp['emp_id_card'] if emp['emp_id_card'] is not None else '',
                        'empGender': emp['emp_gender'] if emp['emp_gender'] is not None else '',
                        'empMarriage': emp['emp_marriage'] if emp['emp_marriage'] is not None else '',
                        'empBirthDay': str(emp['emp_birthday'])[:10] if emp['emp_birthday'] is not None else '',
                        'empPhone': emp['emp_phone'] if emp['emp_phone'] is not None else '',
                        'empGrade': emp['emp_grade'] if emp['emp_grade'] is not None else '',
                        'empDlIDL': emp['emp_dl_idl'] if emp['emp_dl_idl'] is not None else '',
                        'empLaborSource': emp['emp_labour_source'] if emp['emp_labour_source'] is not None else '',
                        'empPoliticalAffiliation': emp['emp_political_affiliation'] if emp['emp_political_affiliation'] is not None else '',
                        'empNationality': emp['emp_nationality'] if emp['emp_nationality'] is not None else '',
                        'empDomicileAddress': emp['emp_domicile_address'] if emp['emp_domicile_address'] is not None else '',
                        'empLatestAddress': emp['emp_latest_address'] if emp['emp_latest_address'] is not None else '',
                        'empUrgentPerson': emp['emp_urgent_person'] if emp['emp_urgent_person'] is not None else '',
                        'empUrgentPhone': emp['emp_urgent_phone'] if emp['emp_urgent_phone'] is not None else '',
                        'empUrgentRelation': emp['emp_urgent_relation'] if emp['emp_urgent_relation'] is not None else '',
                        'empGraduateTime': str(emp['emp_gradute_time'])[:10] if emp['emp_gradute_time'] is not None else '',
                        'empGraduateInsituation': emp['emp_gradute_insituation'] if emp['emp_gradute_insituation'] is not None else '',
                        'empMajor': emp['emp_major'] if emp['emp_major'] is not None else '',
                        'empEducateMethod': emp['emp_educate_method'] if emp['emp_educate_method'] is not None else '',
                        'empBankCardNum': emp['emp_bank_card_num'] if emp['emp_bank_card_num'] is not None else '',
                        'empBank': emp['emp_bank'] if emp['emp_bank'] is not None else '',
                        'empPredictEntryDate': str(emp['emp_predict_entry_date'])[:10] if emp['emp_predict_entry_date'] is not None else '',
                        'approveStatus': approve_status_choices.get(emp['emp_approve_status']),
                        'ethnicId': emp['emp_ethnic_id'] if emp['emp_ethnic_id'] is not None else '',
                        'identityCardList': {'num': identityCardNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/身份证附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/identityCard') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'bankCardList': {'num': bankCardNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/银行卡附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/bankCard') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'resumeList': {'num': resumeFilesNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/简历附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/resumeFiles') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'diplomaPicList': {'num': diplomaFilesNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/毕业证书附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/diplomaFiles') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'affixMaterialList': {'num': affixMaterialNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/非用印材料附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/affixMaterialFiles') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'oneInchPicList': {'num': oneInchFilesNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/一寸照片附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/oneInchFiles') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                        'dissmissPfList': {'num': dissmissPfNum,'url': "http://172.16.12.204:8011" + '/static/empFiles/' + emp['emp_id_card'] + '/离职证明附件.zip' if os.path.exists('static/empFiles/' + emp['emp_id_card'] + '/dissmissPfFiles') else ''} if emp['emp_id_card'] is not None else {'num': identityCardNum, 'url': ''},
                    }
                    return_data['data'].append(temp_dic)
            else:
                return_data['code'] = 200
                return_data['msg'] = '没有相关人员'
                return_data['pageCount'] = 0
        return return_data

    def approve(self, token, id_list, status):
        return_data = {'code': 200, 'msg': ''}
        token_class = Token()
        token_class.token = token
        user_id = token_class.check_token()
        ehr_connect = EhrConnect()
        now = datetime.datetime.now()
        err_msg = ''
        zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,microseconds=now.microsecond) # 获取当天0点的时间
        if user_id:
            user_info = AdminUser.objects.get(id=user_id)
            try:
                for item in id_list:
                    empInfo = ScanEmployee.objects.filter(id=item).values('emp_name', 'emp_code',
                                                                                 'emp_entry_date',
                                                                                 'emp_dept', 'emp_post', 'emp_job_duty',
                                                                                 'emp_job_class', 'emp_job_grade',
                                                                                 'emp_job_rank',
                                                                                 'emp_ethnic', 'emp_native_place',
                                                                                 'emp_pay_type',
                                                                                 'emp_first_degree', 'emp_id_card',
                                                                                 'emp_gender',
                                                                                 'emp_marriage', 'emp_birthday',
                                                                                 'emp_phone', 'emp_grade', 'emp_dl_idl',
                                                                                 'emp_labour_source',
                                                                                 'emp_political_affiliation',
                                                                                 'emp_nationality',
                                                                                 'emp_domicile_address',
                                                                                 'emp_latest_address',
                                                                                 'emp_urgent_person',
                                                                                 'emp_urgent_phone',
                                                                                 'emp_urgent_relation',
                                                                                 'emp_gradute_time',
                                                                                 'emp_gradute_insituation', 'emp_major',
                                                                                 'emp_educate_method',
                                                                                 'emp_bank_card_num',
                                                                                 'emp_bank').first()
                    if status == 3:  # 驳回待入职
                        ScanEmployee.objects.filter(id=item).update(emp_approve_status=status)  # 更新人员状态
                    if status == 2:  # 审批成功
                        #  更新数据库中的入职日期
                        if empInfo['emp_id_card'] is None or empInfo['emp_id_card'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的身份证号,'
                        if empInfo['emp_code'] is None or empInfo['emp_code'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的工号,'
                        if empInfo['emp_dept'] is None or empInfo['emp_dept'] == '' or empInfo['emp_dept'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的部门,'
                        if empInfo['emp_post'] is None or empInfo['emp_post'] == '' or empInfo['emp_post'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的岗位,'
                        if empInfo['emp_job_duty'] is None or empInfo['emp_job_duty'] == '' or empInfo['emp_job_duty'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的职务,'
                        if empInfo['emp_job_class'] is None or empInfo['emp_job_class'] == '' or empInfo['emp_job_class'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的职等,'
                        if empInfo['emp_job_grade'] is None or empInfo['emp_job_grade'] == '' or empInfo['emp_job_grade'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的职级,'
                        if empInfo['emp_job_rank'] is None or empInfo['emp_job_rank'] == '' or empInfo['emp_job_rank'] == 999:
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的合同归属,'
                        if empInfo['emp_id_card'] is None or empInfo['emp_id_card'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的身份证,'
                        if empInfo['emp_gender'] is None or empInfo['emp_gender'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的性别,'
                        if empInfo['emp_birthday'] is None or empInfo['emp_birthday'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的出生日期,'
                        if empInfo['emp_phone'] is None or empInfo['emp_phone'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的手机号码,'
                        if empInfo['emp_dl_idl'] is None or empInfo['emp_dl_idl'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的DL/IDL/SAL,'
                        if empInfo['emp_labour_source'] is None or empInfo['emp_labour_source'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的劳务来源,'
                        if empInfo['emp_political_affiliation'] is None or empInfo['emp_political_affiliation'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的政治面貌,'
                        if empInfo['emp_nationality'] is None or empInfo['emp_nationality'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的国籍,'
                        if empInfo['emp_domicile_address'] is None or empInfo['emp_domicile_address'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的户籍地址,'
                        if empInfo['emp_latest_address'] is None or empInfo['emp_latest_address'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的现住址,'
                        if empInfo['emp_urgent_person'] is None or empInfo['emp_urgent_person'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的紧急联系人,'
                        if empInfo['emp_urgent_phone'] is None or empInfo['emp_urgent_phone'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的紧急联系人电话,'
                        if empInfo['emp_urgent_relation'] is None or empInfo['emp_urgent_relation'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的紧急联系人关系,'
                        if empInfo['emp_bank_card_num'] is None or empInfo['emp_bank_card_num'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的银行卡号,'
                        if empInfo['emp_bank'] is None or empInfo['emp_bank'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的开户行,'
                        if empInfo['emp_pay_type'] is None or empInfo['emp_pay_type'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的计薪方式,'
                        if empInfo['emp_grade'] is None or empInfo['emp_grade'] == '':
                            err_msg = err_msg + '请添加姓名为：' + empInfo['emp_name'] + '的等级,'
                        if err_msg != '':
                            return_data['code'] = 500
                            return_data['msg'] = err_msg
                            continue
                        ScanEmployee.objects.filter(id=item).update(emp_approve_status=status)  # 更新人员状态
                        ScanEmployee.objects.filter(id=item).update(emp_entry_date=zero_today)  # 更新人员入职时间
                        ehr_connect.update(
                            "IF NOT EXISTS (SELECT Code FROM T_HR_Employee WHERE Code = '%s') INSERT INTO T_HR_Employee (ID,Name,_jtrzrq,DeptID,PostID,JobID,JobClassID,JobGradeID,JobRankID,identityNumber,Sex,Birthday,phone,_gsgs,PayTypeID,_dlidl,qq,Code,_zzmm,_gj,NationID,HomeAddress,_xzz,HomeID,marriage,_jjlxr,_lxrdh,_guanxi,DegreeID,_bysj,_yuanxiao,_zhuanye,_jyfs,_kahao,_khh,CreatorCode,Creator,CreateTime,FpCode,identityType,_ifoazh,HireDate,ModifyTime) VALUES ( (SELECT MAX(ID)+1 from T_HR_Employee),'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') ELSE Update T_HR_Employee set Name='%s',_jtrzrq='%s',DeptID='%s',PostID='%s',JobID='%s',JobClassID='%s',JobGradeID='%s',JobRankID='%s',identityNumber='%s',Sex='%s',Birthday='%s',phone='%s',_gsgs='%s',PayTypeID='%s',_dlidl='%s',qq='%s',Code='%s',_zzmm='%s',_gj='%s',NationID='%s',HomeAddress='%s',_xzz='%s',HomeID='%s',marriage='%s',_jjlxr='%s',_lxrdh='%s',_guanxi='%s',DegreeID='%s',_bysj='%s',_yuanxiao='%s',_zhuanye='%s',_jyfs='%s',_kahao='%s',_khh='%s',ModifierCode='%s',Modifier='%s',ModifyTime='%s',FpCode='%s' where Code='%s'"
                            % (empInfo['emp_code'],
                               empInfo['emp_name'],
                               str(zero_today)[:19] + '.000',  # 集团入职日期
                               empInfo['emp_dept'],  # 部门
                               empInfo['emp_post'],  # 岗位
                               empInfo['emp_job_duty'],  # 职务
                               empInfo['emp_job_class'],  # 职等
                               empInfo['emp_job_grade'],  # 职级
                               empInfo['emp_job_rank'],  # 合同归属
                               empInfo['emp_id_card'],  # 身份证
                               empInfo['emp_gender'],  # 性别
                               str(empInfo['emp_birthday']) + '.000',  # 出生日期
                               empInfo['emp_phone'] if empInfo['emp_phone'] is not None else '',  # 手机号码
                               empInfo['emp_grade'] if empInfo['emp_grade'] is not None else '',  # 人员等级
                               empInfo['emp_pay_type'] if empInfo['emp_pay_type'] is not None else '',  # 计薪方式
                               empInfo['emp_dl_idl'] if empInfo['emp_dl_idl'] is not None else '',  # DL/IDL
                               empInfo['emp_labour_source'] if empInfo['emp_labour_source'] is not None else '',  # 劳务来源
                               empInfo['emp_code'] if empInfo['emp_code'] is not None else '', # 工号
                               empInfo['emp_political_affiliation'] if empInfo['emp_political_affiliation'] is not None else '', # 政治面貌
                               empInfo['emp_nationality'] if empInfo['emp_nationality'] is not None else '',  # 国籍
                               empInfo['emp_ethnic'] if empInfo['emp_ethnic'] is not None else '',  # 民族
                               empInfo['emp_domicile_address'] if empInfo['emp_domicile_address'] is not None else '', # 户籍地址
                               empInfo['emp_latest_address'] if empInfo['emp_latest_address'] is not None else '', # 现住址
                               empInfo['emp_native_place'] if empInfo['emp_native_place'] is not None else '',  # 人员籍贯
                               empInfo['emp_marriage'] if empInfo['emp_marriage'] is not None else '', # 婚姻状况
                               empInfo['emp_urgent_person'] if empInfo['emp_urgent_person'] is not None else '', # 紧急联系人姓名
                               empInfo['emp_urgent_phone'] if empInfo['emp_urgent_phone'] is not None else '', # 紧急联系人电话
                               empInfo['emp_urgent_relation'] if empInfo['emp_urgent_relation'] is not None else '', # 紧急联系人关系
                               empInfo['emp_first_degree'] if empInfo['emp_first_degree'] is not None else '', # 第一学历
                               str(empInfo['emp_gradute_time'])[:19] + '.000',  # 毕业时间
                               empInfo['emp_gradute_insituation'] if empInfo['emp_gradute_insituation'] is not None else '', # 毕业院校
                               empInfo['emp_major'] if empInfo['emp_major'] is not None else '', # 毕业专业
                               empInfo['emp_educate_method'] if empInfo['emp_educate_method'] is not None else '', # 教育方式
                               empInfo['emp_bank_card_num'] if empInfo['emp_bank_card_num'] is not None else '', # 银行卡号
                               empInfo['emp_bank'] if empInfo['emp_bank'] is not None else '', # 开户行
                               str(user_info.username),  # 创建人
                               str(user_info.account),  # 创建人
                               str(now)[:19] + '.000',  # 创建时间
                               empInfo['emp_code'],  # 登记号同工号写入
                               '1',  # 身份证件默认为 身份证 后续不对SSC修改
                               '是',  # EHR中是否有OA账号默认为是
                               str(zero_today)[:19] + '.000',  # 入职时间
                               str(now)[:19] + '.000',  # 修改时间

                                # 有记录就更新
                               empInfo['emp_name'],
                               str(zero_today)[:19] + '.000',
                               empInfo['emp_dept'],
                               empInfo['emp_post'],
                               empInfo['emp_job_duty'],
                               empInfo['emp_job_class'],
                               empInfo['emp_job_grade'],
                               empInfo['emp_job_rank'],
                               empInfo['emp_id_card'],
                               empInfo['emp_gender'],
                               str(empInfo['emp_birthday']) + '.000',
                               empInfo['emp_phone'] if empInfo['emp_phone'] is not None else '',
                               empInfo['emp_grade'] if empInfo['emp_grade'] is not None else '',
                               empInfo['emp_pay_type'],
                               empInfo['emp_dl_idl'] if empInfo['emp_dl_idl'] is not None else '',
                               empInfo['emp_labour_source'] if empInfo['emp_labour_source'] is not None else '',
                               empInfo['emp_code'],
                               empInfo['emp_political_affiliation'] if empInfo['emp_political_affiliation'] is not None else '',
                               empInfo['emp_nationality'] if empInfo['emp_nationality'] is not None else '',
                               empInfo['emp_ethnic'],
                               empInfo['emp_domicile_address'] if empInfo['emp_domicile_address'] is not None else '',
                               empInfo['emp_latest_address'] if empInfo['emp_latest_address'] is not None else '',
                               empInfo['emp_native_place'] if empInfo['emp_native_place'] is not None else '',
                               empInfo['emp_marriage'] if empInfo['emp_marriage'] is not None else '',
                               empInfo['emp_urgent_person'] if empInfo['emp_urgent_person'] is not None else '',
                               empInfo['emp_urgent_phone'] if empInfo['emp_urgent_phone'] is not None else '',
                               empInfo['emp_urgent_relation'] if empInfo['emp_urgent_relation'] is not None else '',
                               empInfo['emp_first_degree'] if empInfo['emp_first_degree'] is not None else '',
                               str(empInfo['emp_gradute_time'])[:19] + '.000',
                               empInfo['emp_gradute_insituation'] if empInfo['emp_gradute_insituation'] is not None else '',
                               empInfo['emp_major'] if empInfo['emp_major'] is not None else '',
                               empInfo['emp_educate_method'] if empInfo['emp_educate_method'] is not None else '',
                               empInfo['emp_bank_card_num'] if empInfo['emp_bank_card_num'] is not None else '',
                               empInfo['emp_bank'] if empInfo['emp_bank'] is not None else '',
                               str(user_info.username),
                               str(user_info.account),
                               str(now)[:19] + '.000',
                               empInfo['emp_code'],  # 登记号同工号进行写入
                               empInfo['emp_code'],  # 根据工号进行匹配信息
                               ))
                if err_msg == '':
                    return_data['code'] = 200
                    return_data['msg'] = '审批成功'
                else:
                    return_data['code'] = 500
                    return_data['msg'] = err_msg[:-1]
            except Exception as e:
                print(e)
                return_data['code'] = 500
                return_data['msg'] = '发生错误'
        return return_data


class DropList:
    ''' 获取民族列表 '''

    def nationDrop(self):
        return_data = {'code': "", "message": ""}
        nation_obj = ScanEnthic.objects.filter(enthic_status=True).values('id', 'enthic_name')
        nationList = []
        for datas in nation_obj:
            temp_dic = {
                'value': datas['id'],
                'label': datas['enthic_name']
            }
            nationList.append(temp_dic)
        return_data['code'] = 200
        return_data['message'] = '获取民族列表成功'
        return_data['data'] = {}
        return_data['data']['nationList'] = nationList
        return return_data

    '''获取籍贯下拉列表'''

    def nativePlaceDrop(self):
        return_data = {'code': "", "message": ""}
        native_obj = ScanNative.objects.filter(native_status=True).values('id', 'native_name')
        nativeList = []
        for datas in native_obj:
            temp_dic = {
                'value': datas['id'],
                'label': datas['native_name']
            }
            nativeList.append(temp_dic)
        return_data['code'] = 200
        return_data['message'] = '获取籍贯列表成功'
        return_data['data'] = {}
        return_data['data']['nativeList'] = nativeList
        return return_data


def select_options(token):
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        # 部门下拉
        return_data = {'code': '', "msg": '', 'data': {'deptOption': [], 'positionOption': [], 'jobDutyObj': []}}
        tree_code_cmp = EmpDepartment.objects.filter().extra(select={'label': 'department_full_name', 'value': 'id'}).values('value', 'label','department_level').order_by('department_level')
        # total_tree_data = get_trees(tree_code_cmp, 'value', 'parent_id')
        return_data['code'] = 200
        return_data['msg'] = '获取部门成功'
        return_data['data']['deptOption'] = list(tree_code_cmp)
        # 岗位下拉
        positionObj = EmpPosition.objects.filter().extra(select={'label': 'post_name', 'value': 'id'}).values('value','label')
        return_data['data']['positionOption'] = list(positionObj)
        # 职务
        jobDutyObj = EmpJobDuty.objects.filter().extra(select={'label': 'job_duty_name', 'value': 'id'}).values('value','label')
        return_data['data']['jobDutyOption'] = list(jobDutyObj)
        # 职等
        jobClassObj = EmpJobClass.objects.filter().extra(select={'label': 'job_class_name', 'value': 'id'}).values('value', 'label')
        return_data['data']['jobClassOption'] = list(jobClassObj)
        # 职级
        jobGradeObj = EmpJobGrade.objects.filter().extra(select={'label': 'job_grade_name', 'value': 'id'}).values('value', 'label')
        return_data['data']['jobGradeOption'] = list(jobGradeObj)
        # 合同归属
        jobRankObj = EmpJobRank.objects.filter().extra(select={'label': 'job_rank_name', 'value': 'id'}).values('value','label')
        return_data['data']['jobRankOption'] = list(jobRankObj)
        # 计薪方式
        payTypeObj = EmpPayType.objects.filter().extra(select={'label': 'pay_type_name', 'value': 'id'}).values('value','label')
        return_data['data']['payTypeOption'] = list(payTypeObj)
        return return_data


def positionOptions(token):
    token_class = Token()
    token_class.token = token
    user_id = token_class.check_token()
    if user_id:
        return_data = {'code': '', "msg": '', 'data': []}
        positionObj = EmpPosition.objects.filter().extra(select={'label': 'post_name', 'value': 'id'}).values('value','label')
        return return_data
